﻿// Singleton to keep a dictionary of components indexed by their ids
define([],
function () {
    'use strict';

    // Dictionary to store the instances of the components mapped by their ids
    var components = {},
        copyOrReplaceMembers = function (to, from) {
            for (var name in from) {
                if (from.hasOwnProperty(name)) {
                    to[name] = from[name];
                }
            }
        };

    return {

        // Registers the instance of the component to allow its retrieval anywhere by its id
        register: function (cmp, id) {
            var cmpId = cmp.id || id;

            if (!cmpId) {
                throw 'Cannot register an instance without id';
            }

            if (components[cmpId]) { // Check for unique ids of the registered components
                throw "Component with id:'" + cmpId + "' is already registered'";
            }

            components[cmpId] = cmp;
        },

        // Removes a component from the hash of components
        remove: function (id) {

            if (components[id]) { // Check for unique ids of the registered components

                delete components[id];

                return true;
            }

            return false; // Component was not found
        },

        // Retrieves the component by its id, if there is a conf, then a new object is created copying the members of the original object and the configuration one
        get: function (id, conf) {
            var o = components[id],
                n;

            if (conf) {

                n = {};
                copyOrReplaceMembers(n, o);
                copyOrReplaceMembers(n, conf);

                return n;
            }

            return o;
        }
    };

});